#-*- coding:utf-8 -*-
'''
Created on 12.02.2010

@author: hu1salh1
'''
import hashlib
class WMI_PAUK(object):
    '''
    Модуль считывания информации из Windows по средствам WMI 
    '''
    def __init__(self):
        '''
        Constructor
        '''
        import wmi
        c=wmi.WMI()
        def hasher(x):
            HASH="md5"
            h=hashlib.new(HASH)
            h.update(x)
            return h.hexdigest()
        def getInfo(name,param):        #стандартная фунция WQL для считывания нужных полей
            params = ",".join(param)    #формирование одного длинного параметра путем канкатенации перечисленых полей
            wql = "select %s from Win32_%s"%(params,name)   #шаблон для формирования запроса
            return c.query(wql)
        def BaseBoard():                    #материнская плата
            ID_Desc_list={}
            device="BaseBoard"
            field=["Caption","Product","SerialNumber"]
            for data in getInfo(device,field):
                ID=hasher(data.SerialNumber)
                #ID=data.SerialNumber
                Descript=",".join((data.Caption,data.Product))
                ID_Desc_list[ID]=Descript
            return ID_Desc_list
        def Processor():                    #процессор
            ID_Desc_list={}
            device="Processor"
            field=["Name","ProcessorID"]
            for data in getInfo(device,field):
                ID=hasher(data.ProcessorID)
                Descript=data.Name
                ID_Desc_list[ID]=Descript
            return ID_Desc_list
        def MemoryDevice():                 #оперативная память
            size=0
            ID_Desc_list={}
            device="MemoryDevice"
            field=["Caption","EndingAddress","SystemName"]
            for data in getInfo(device,field):
                if size < data.EndingAddress:
                    size = data.EndingAddress
                    opera_name= ",".join((data.SystemName,data.Caption))
                    Descript= " ,".join((data.Caption,size))
                    ID=hasher(opera_name)
                ID_Desc_list[ID]=Descript
            return ID_Desc_list
        def Keyboard():                     #клавиатура
            ID_Desc_list={}
            device="Keyboard"
            field=["Caption","DeviceID"]
            for data in getInfo(device,field):
                ID=hasher(data.DeviceID)
                Descript=data.Caption
                ID_Desc_list[ID]=Descript
            return ID_Desc_list
        def PointingDevice():                   #мышь
            ID_Desc_list={}
            device="PointingDevice"
            field=["Description","PNPDeviceID"]
            for data in getInfo(device,field):
                Descript=data.Description
                ID=hasher(data.PNPDeviceID)
                ID_Desc_list[ID]=Descript
            return ID_Desc_list
        def SoundDevice():                          #звуковая карта
            ID_Desc_list={}
            device="SoundDevice"
            field=["Description","PNPDeviceID"]
            for data in getInfo(device,field):
                Descript=data.Description
                ID=hasher(data.PNPDeviceID)
                ID_Desc_list[ID]=Descript
            return ID_Desc_list
        def VideoController():                      #видео карта
            ID_Desc_list={}
            device="VideoController"
            field=["Description","PNPDeviceID"]
            for data in getInfo(device,field):
                Descript=data.Description
                ID=hasher(data.PNPDeviceID)
                ID_Desc_list[ID]=Descript
            return ID_Desc_list
        def NetworkAdapterConfiguration():                      # конфигурация сетевых карт             
            import re
            pattern = r"\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"
            adress = re.compile(pattern)
            ID_Desc_list={}
            device="NetworkAdapterConfiguration"
            field=["ServiceName","IPAddress","MACAddress","IPEnabled"]
            for data in getInfo(device,field):
                if data.IPEnabled==0: continue                                                      
                NetFlag.append(data.ServiceName)
                ID_Desc_list['IP']=data.IPAddress
                ID_Desc_list['MAC']=data.MACAddress
            return ID_Desc_list
        def NetworkAdapter():                                   #сетевая карта
            ID_Desc_list={}
            device="NetworkAdapter"
            field=["MACAddress","PNPDeviceID","ProductName","ServiceName"]
            for data in getInfo(device,field):
                if unicode([data.ServiceName]) != unicode(NetFlag):continue
                ID=hasher(data.PNPDeviceID)
                Descript=" * ".join((data.ProductName,data.MACAddress))
                ID_Desc_list[ID]=Descript
            return ID_Desc_list
        def DesktopMonitor():                                   #монитор
            ID_Desc_list={}
            device="DesktopMonitor"
            field=["Description","PNPDeviceID"]
            for data in getInfo(device,field):
                Descript=data.Description
                ID=hasher(data.PNPDeviceID)
                ID_Desc_list[ID]=Descript
            return ID_Desc_list
        def FloppyDrive():                                      #дисковод
            ID_Desc_list = {}
            device="FloppyDrive"
            field=["Caption","PNPDeviceID"]
            for data in getInfo(device,field):
                ID=hasher(data.PNPDeviceID)
                Descript=data.Caption
                ID_Desc_list[ID]=Descript
            return ID_Desc_list
        def DiskDrive():                                        # жесткий диск и тд
            ID_Desc_list = {}
            device="DiskDrive"
            field=["Model","SerialNumber","SystemName"]
            for data in getInfo(device,field):
                if data.SerialNumber==None:
                    SerialNumber=",".join((data.Model,data.SystemName))
                    ID=hasher(SerialNumber)
                else:
                    ID=hasher(data.SerialNumber)
                Descript=data.Model
                ID_Desc_list[ID]=Descript
        #    print ID_Desc_list
            return ID_Desc_list
        def CDROMDrive():                                       # CD-ROM
            ID_Desc_list={}
            device="CDROMDrive"
            field=["Name","PNPDeviceID"]
            for data in getInfo(device,field):
                Descript=data.Name
                ID=hasher(data.PNPDeviceID)
                ID_Desc_list[ID]=Descript
            return ID_Desc_list
        def InfraredDevice():                                   # видимо IRC устройство
            ID_Desc_list={}
            device="InfraredDevice"
            field=["Caption","PNPDeviceID"]
            for data in getInfo(device,field):
                Descript=data.Caption
                ID=hasher(data.PNPDeviceID)
                ID_Desc_list[ID]=Descript
            return ID_Desc_list
        def Printer():                                      # принтер
            ID_Desc_list={}
            device="Printer"
            field=["Caption","DeviceID","ShareName","SystemName"]
            for data in getInfo(device,field):
                if data.ShareName==None: continue   
                IDtemp=",".join((data.DeviceID,data.SystemName))
                ID=hasher(IDtemp)
                Descript= data.Caption+" ShareName: "+data.ShareName
                sys=hasher(data.SystemName)
                ID_Desc_list['SYSTEM_N']=sys
                ID_Desc_list['SYSTEM_C']=data.SystemName
                ID_Desc_list[ID]=Descript
            return ID_Desc_list
        def Refrigeration():                                # система охлаждения
            ID_Desc_list={}
            device="Refrigeration"
            field=["Caption","PNPDeviceID"]
            for data in getInfo(device,field):
                Descript=data.Caption
                ID=hasher(data.PNPDeviceID)
                ID_Desc_list[ID]=Descript
            return ID_Desc_list
        def TapeDrive():                                    # носитель на магнитной ленте
            ID_Desc_list={}
            device="TapeDrive"
            field=["Caption","PNPDeviceID"]
            for data in getInfo(device,field):
                Descript=data.Caption
                ID=hasher(data.PNPDeviceID)
                ID_Desc_list[ID]=Descript
            return ID_Desc_list
        # очередность вызова функций
        DeviceList=[BaseBoard,Processor,MemoryDevice,Keyboard,PointingDevice,SoundDevice,VideoController,\
                 NetworkAdapterConfiguration,NetworkAdapter,DesktopMonitor,FloppyDrive,DiskDrive,CDROMDrive,\
                 InfraredDevice,Printer,Refrigeration,TapeDrive]
        NetFlag=[]                      # глобальная переменная чтобы передать идентификатор реальной сетевой карты
        Information = {}                # формирование конечного словаря путем считывания словарей из вызываемых функций
        for f in DeviceList:
            runtimeDict = f()
            Information.update(runtimeDict)
        self.result=Information